package com.cloud.wms.ui.returned.inventory;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatImageView;

import com.cloud.core.eventBus.Event;
import com.cloud.printer.esc.Text;
import com.cloud.widget.ScanText;
import com.cloud.wms.R;
import com.cloud.wms.base.BaseBarActivity;
import com.cloud.wms.config.EventConfig;
import com.cloud.wms.config.IntentKey;
import com.cloud.wms.ui.returned.contact.InventoryContract;
import com.cloud.wms.ui.returned.entity.InventoryInfoEntity;
import com.cloud.wms.ui.returned.presenter.InventoryPresenter;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @Author： Chen
 * @Date： 2021/5/19
 * @Desc：
 */
public class InventoryActivity extends BaseBarActivity<InventoryPresenter> implements InventoryContract.View {
    @BindView(R.id.scan_text)
    ScanText scanText;
    @BindView(R.id.tv_returned_carry_code)
    TextView tvReturnedCarryCode;
    @BindView(R.id.tv_commodity_code)
    TextView tvCommodityCode;
    @BindView(R.id.ll_commodity_code)
    LinearLayout llCommodityCode;
    @BindView(R.id.tv_commodity_name)
    TextView tvCommodityName;
    @BindView(R.id.ll_commodity_name)
    LinearLayout llCommodityName;
    @BindView(R.id.btn_good)
    CheckedTextView btnGood;
    @BindView(R.id.btn_bad)
    CheckedTextView btnBad;
    @BindView(R.id.ll_commodity_type)
    LinearLayout llCommodityType;
    @BindView(R.id.et_returned_logistics_code)
    EditText etReturnedLogisticsCode;
    @BindView(R.id.ll_logistics_code)
    LinearLayout llLogisticsCode;
    @BindView(R.id.tv_select_batch)
    TextView tvSelectBatch;
    @BindView(R.id.iv_select_batch)
    AppCompatImageView ivSelectBatch;
    @BindView(R.id.ll_select_batch)
    LinearLayout llSelectBatch;
    @BindView(R.id.tv_produce_date)
    TextView tvProduceDate;
    @BindView(R.id.iv_produce_date)
    ImageView ivProduceDate;
    @BindView(R.id.tv_deadline_date)
    TextView tvDeadlineDate;
    @BindView(R.id.iv_deadline_date)
    ImageView ivDeadlineDate;
    @BindView(R.id.tv_in_date)
    TextView tvInDate;
    @BindView(R.id.iv_in_date)
    ImageView ivInDate;
    @BindView(R.id.ll_batch)
    LinearLayout llBatch;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.btn_next)
    TextView btnNext;
    private InventoryInfoEntity inventoryInfo;
    // 是否为无头件
    private boolean isHeadless;
    private InventoryInfoEntity.CommodityListBean commodityBean;
    private InventoryInfoEntity.CommodityListBean.BatchInfoBean batchInfoBean;
    private boolean isVerifyBox = false;
    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            verifyRequired();
        }
    };

    @Override
    protected String barTitle() {
        return "退货清点";
    }

    @Override
    protected int getResId() {
        return R.layout.activity_returned_inventory;
    }

    @Override
    protected void setupComponent() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void initEvent() {
        initScanText(scanText);
        inventoryInfo = getIntent().getParcelableExtra(IntentKey.OBJECT_KEY);
        isHeadless = TextUtils.isEmpty(inventoryInfo.getShipOrderCode());

        initView(inventoryInfo);
        etReturnedLogisticsCode.addTextChangedListener(textWatcher);
    }

    private void initView(InventoryInfoEntity inventoryInfo) {
        tvReturnedCarryCode.setText(inventoryInfo.getExpressDeliveryCode());
        llCommodityCode.setVisibility(View.GONE);
        llCommodityName.setVisibility(View.GONE);
        llCommodityType.setVisibility(View.GONE);
        llBatch.setVisibility(View.GONE);
        llSelectBatch.setVisibility(View.GONE);

        ivDeadlineDate.setVisibility(View.GONE);
        ivInDate.setVisibility(View.GONE);
        ivProduceDate.setVisibility(View.GONE);

        etReturnedLogisticsCode.setText("");
        tvCommodityCode.setText("");
        tvCommodityName.setText("");
        tvDeadlineDate.setText("");
        tvInDate.setText("");
        tvProduceDate.setText("");

        scanText.setHint("商品条码");
        scanText.setText("");

        tvDeadlineDate.setHint("");
        tvInDate.setHint("");
        tvProduceDate.setHint("");

        ivDeadlineDate.setVisibility(View.GONE);
        ivInDate.setVisibility(View.GONE);
        ivProduceDate.setVisibility(View.GONE);

        btnGood.setChecked(true);
        btnBad.setChecked(false);

        btnNext.setEnabled(false);
        btnSubmit.setEnabled(false);

        isVerifyBox = false;
    }

    @Override
    protected void onScanHandle(String result, int resultCode) {
        super.onScanHandle(result, resultCode);
        if (etReturnedLogisticsCode.isFocused() && commodityBean.isNeedLogistics()) {
            success("物流码已录入！");
        } else if (isVerifyBox) {
            mPresenter.checkBoxCode(result);
        } else {
            scanText.addHistory(result);
            if (isHeadless) {
                mPresenter.queryCommodity(result);
            } else {
                for (int i = 0; i < inventoryInfo.getCommodityList().size(); i++) {
                    InventoryInfoEntity.CommodityListBean bean = inventoryInfo.getCommodityList().get(i);
                    if (bean.matchBarCode(result)) {
                        setDataToView(bean);
                        return;
                    }
                }
                info("该商品不属于当前退货单！");
            }
        }
    }

    private void setDataToView(InventoryInfoEntity.CommodityListBean bean) {
        isVerifyBox = true;
        commodityBean = bean;
        tvCommodityName.setText(bean.getCommodityName());
        tvCommodityCode.setText(bean.getBarCode());
        llCommodityCode.setVisibility(View.VISIBLE);
        llCommodityName.setVisibility(View.VISIBLE);
        llCommodityType.setVisibility(View.VISIBLE);
        llSelectBatch.setVisibility(View.VISIBLE);

        if (bean.isNeedLogistics()) {
            etReturnedLogisticsCode.setOnKeyListener(onKeyListenerImp);
            llLogisticsCode.setVisibility(View.VISIBLE);
        }

        info("请选择批次和扫描容器！");
        scanText.setHint("容器号");
    }

    @Override
    public void onSuccess(Message message) {
        switch (message.what) {
            case InventoryPresenter.CHECK_RETURNED_BOX:
                success("容器扫描成功！");
                scanText.setText(message.obj.toString());
                scanText.setSelection(message.obj.toString().length());
                verifyRequired();
                break;
            case InventoryPresenter.CHECK_RETURNED_COMMODITY:
                setDataToView((InventoryInfoEntity.CommodityListBean) message.obj);
                break;
            case InventoryPresenter.CONFIRM_RETURN_INVENTORY:
                success("清点成功！");
                if (((boolean) message.obj)) {
                    mPresenter.getReturnedInfo(inventoryInfo.getExpressDeliveryCode());
                } else {
                    this.finish();
                }
                break;
            case InventoryPresenter.GET_RETURNED_COMMODITY:
                inventoryInfo = ((InventoryInfoEntity) message.obj);
                isHeadless = TextUtils.isEmpty(inventoryInfo.getShipOrderCode());
                if (!isHeadless && (inventoryInfo.getCommodityList() == null || inventoryInfo.getCommodityList().isEmpty())) {
                    info("当前退货快递单无可清点商品！");
                    this.finish();
                    return;
                }
                initView(inventoryInfo);
                break;
        }
    }

    private void verifyRequired() {
        if (!isVerifyBox) {
            btnSubmit.setEnabled(false);
            btnNext.setEnabled(false);
            return;
        }

        String logisticsCode = etReturnedLogisticsCode.getText().toString().trim();
        if (TextUtils.isEmpty(logisticsCode) && commodityBean.isNeedLogistics()) {
            btnSubmit.setEnabled(false);
            btnNext.setEnabled(false);
            return;
        }
        String boxCode = scanText.getText().toString().trim();
        if (TextUtils.isEmpty(boxCode) && isVerifyBox) {
            btnSubmit.setEnabled(false);
            btnNext.setEnabled(false);
            return;
        }
        if (llBatch.getVisibility() != View.VISIBLE) {
            btnSubmit.setEnabled(false);
            btnNext.setEnabled(false);
            return;
        }

        btnSubmit.setEnabled(true);
        btnNext.setEnabled(true);
    }

    @OnClick({R.id.tv_inventory_detail, R.id.btn_good, R.id.btn_bad, R.id.tv_select_batch, R.id.iv_select_batch, R.id.btn_submit, R.id.btn_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_inventory_detail:
                InventoryDetailActivity.start(this, inventoryInfo.getExpressDeliveryCode());
                break;
            case R.id.btn_good:
                btnGood.setChecked(true);
                btnBad.setChecked(false);
                break;
            case R.id.btn_bad:
                btnGood.setChecked(false);
                btnBad.setChecked(true);
                break;
            case R.id.tv_select_batch:
            case R.id.iv_select_batch:
                if (isHeadless || commodityBean.getBatchInfo() == null || commodityBean.getBatchInfo().isEmpty()) {
                    EditBatchActivity.start(this, batchInfoBean);
                } else {
                    SelectBatchActivity.start(this, commodityBean.getBatchInfo());
                }
                break;
            case R.id.btn_submit:
                commodityBean.setLogisticsCode(etReturnedLogisticsCode.getText().toString());
                commodityBean.setStockType(btnGood.isChecked() ? 1 : 2);
                mPresenter.submitReturnedInventory(inventoryInfo.getExpressDeliveryCode(), scanText.getText(), commodityBean, batchInfoBean, false);
                break;
            case R.id.btn_next:
                commodityBean.setLogisticsCode(etReturnedLogisticsCode.getText().toString());
                commodityBean.setStockType(btnGood.isChecked() ? 1 : 2);
                mPresenter.submitReturnedInventory(inventoryInfo.getExpressDeliveryCode(), scanText.getText(), commodityBean, batchInfoBean, true);
                break;
        }
    }

    @Override
    protected boolean isUseEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onEventCome(Event event) {
        if (event == null) {
            return;
        }
        switch (event.getCode()) {
            case EventConfig.SWITCH_BATCH:
                batchInfoBean = ((InventoryInfoEntity.CommodityListBean.BatchInfoBean) event.getData());
                llBatch.setVisibility(View.VISIBLE);
                tvInDate.setText(batchInfoBean.getInDate());
                tvDeadlineDate.setText(batchInfoBean.getExpirationDate());
                tvProduceDate.setText(batchInfoBean.getProductionDate());
                verifyRequired();
                break;
        }
    }

    public static void start(Context context, InventoryInfoEntity infoEntity) {
        Intent intent = new Intent(context, InventoryActivity.class);
        intent.putExtra(IntentKey.OBJECT_KEY, infoEntity);
        context.startActivity(intent);
    }
}
